#include "Log.hpp"
#include <string>
#include <vector>
#include "Inet_Addr.hpp"

//消息的发送顺序: client -> server -> route -> 所有client
class route//路由
{
private:
    bool is_exist(const Inet_Addr& user)
    {
        for(const auto& u : _online_users)
        {
            if(u == user)
                return true;
        }
        return false;
    }

    void add_user(const Inet_Addr& user)
    {
        _online_users.push_back(user);
        LOG(wzx::log_level::INFO) << "add a new member";
    }

    void erase_user(const Inet_Addr& user)
    {
        auto it = _online_users.begin();
        while(it != _online_users.end())
        {
            if(*it == user)
            {
                _online_users.erase(it);
                LOG(wzx::log_level::INFO) << "delete a member";
                break;
            }
            it++;
        }  
    }

public:
    void message_route(int socket_fd, const std::string& message, const Inet_Addr& user)
    {
        if(!is_exist(user))
            add_user(user);

        std::string send_message = "\"" + user.get_ip() + std::to_string(user.get_port()) + "\":> " + message;

        for(const auto& u : _online_users)
        {
            sendto(socket_fd, send_message.c_str(), send_message.size(), 0, (const sockaddr*)&u.get_addr(), sizeof(u.get_addr()));
        }

        if(message == "quit")
            erase_user(user);
    }


private:
    std::vector<Inet_Addr> _online_users;
};